package org.colin.face.util;

import lombok.extern.slf4j.Slf4j;
import org.colin.code.BaseResponseCode;
import org.colin.exception.ServiceException;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Description: 文件读取工具
 * @ClassName: FileUtil
 * @Author: wujiangbo
 * @Date: 2020/9/3 0003 13:28
 * @Version: 1.1.0
 */
@Slf4j
public class FileUtil {

    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }
        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }
        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入�?
        FileInputStream fis = new FileInputStream(filePath);
        // 创建�?个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ((hasRead = fis.read(bbuf)) > 0) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new ServiceException(BaseResponseCode.FILE_NOT_FOUND);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;
            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }
                byte[] var7 = bos.toByteArray();
                return var7;
            }catch(Exception e) {
                log.error("根据文件路径读取byte[]数组异常：{}", e.getLocalizedMessage());
            }finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
            }
        }
        return null;
    }
}
